<?php
/**
 * @package Admin
 * @author Henrique Droog <henridroog@gmail.com>
 * @name ModuleController
 * @since 19/03/2011
 * @version 1.0
 */
class Admin_ModuleController extends Zend_Controller_Action
{
    protected $_form;
    protected $_modules;
    protected $_moduleMapper;
    protected $_request;

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        $_modules = new Admin_Model_ModuleMapper();
        $this->view->entries = $_modules->fetchAll();
    }

    private function getForm(){
        $form = new Admin_Form_ModuleForm();
        $form->setAction(Zend_Controller_Front::getInstance()->getBaseUrl().'/admin/module/add/')
             ->setMethod('post')
             ->setAttrib('id','form');

        return $form;
    }

    public function addAction()
    {
        $this->_form = $this->getForm();
        $request = $this->getRequest();
        if ($this->getRequest()->isPost()) {
            if ($this->_form->isValid($request->getPost())) {
                $module = new Admin_Model_Module($this->_form->getValues());
                $mapper = new Admin_Model_ModuleMapper();
                $mapper->save($module);
                return $this->_helper->redirector('index');
            } else {
                $this->_form->populate($this->_request->getPost());
            }
        }
        $this->view->form = $this->_form;
        //$this->view->render('add.phtml');
    }

    public function editAction()
    {
        $this->_form = $this->getForm();
        $request = $this->getRequest();
        $id['id'] = $request->getParam('id');
        if ($id!='') {
           $module = new Admin_Model_Module($id);
           $mapper = new Admin_Model_ModuleMapper();
           $res = $mapper->find($id, $module);
           $dataForm["id"] = $res->id;
           $dataForm["name"] = $res->name;
           if(count($res)>=1){
               $this->_form->populate($dataForm);
           }
        }
       // die();
        $this->view->form = $this->_form;
    }

    public function deleteAction()
    {
        $request = $this->getRequest();
        $id['id'] = $request->getParam('id');
        if ($id!='') {
            $module = new Admin_Model_Module($id);
            $mapper = new Admin_Model_ModuleMapper();
            $res = $mapper->del($module);
        }
        return $this->_helper->redirector('index');
    }
}